package com.itouch.bracelet.activity;

import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.bean.MedPercentAndSport;
import com.itouch.bracelet.bean.MedPercentAndSportResult;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.LoadingDialog;
import com.itouch.widget.ActionSheet;
import com.itouch.widget.ActionSheet.ActionSheetListener;
import com.itouch.widget.circleprogress.DonutProgress;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class MainLeftFragment extends Fragment implements OnClickListener {

	private ImageView medication;
	private LoadingDialog loadingDialog;
	private TextView m_med;
	private TextView mName;
	private TextView mPhone;
	private TextView mDevice;
	private TextView mNextMed;
	private DonutProgress donutProgress;
	private ImageView sport_parent;
	private ImageView m_avatar;
	private LoginUser user;
	private TextView m_step;
	private TextView m_calorie;
	private TextView m_m;
	
	private DisplayImageOptions options;
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragmen_mainleft, null);
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initViews();
	}

	private void initViews() {
		
		options = new DisplayImageOptions.Builder()
		.showImageForEmptyUri(R.drawable.m_default_avatar)
		.showImageOnFail(R.drawable.m_default_avatar)
		.resetViewBeforeLoading(true).cacheOnDisc(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
		.displayer(new FadeInBitmapDisplayer(300)).build();
		
		m_med = (TextView) getActivity().findViewById(R.id.m_med);
		m_calorie = (TextView) getActivity().findViewById(R.id.m_calorie);
		m_m = (TextView) getActivity().findViewById(R.id.m_m);
		m_step = (TextView) getActivity().findViewById(R.id.m_step);
		mName = (TextView) getActivity().findViewById(R.id.m_name);
		mPhone = (TextView) getActivity().findViewById(R.id.m_phone);
		mDevice = (TextView) getActivity().findViewById(R.id.m_device);
		mNextMed = (TextView) getActivity().findViewById(R.id.m_next_med);
		donutProgress = (DonutProgress) getActivity().findViewById(
				R.id.donut_progress);
		sport_parent = (ImageView) getActivity()
				.findViewById(R.id.sport_parent);
		m_avatar = (ImageView) getActivity()
				.findViewById(R.id.m_avatar);
		sport_parent.setOnClickListener(this);
		medication = (ImageView) getActivity().findViewById(R.id.medication);
		medication.setOnClickListener(this);
		m_avatar.setOnClickListener(this);
		
		//加载头像
		ImageLoader.getInstance().displayImage(UserCache.getOauth(getActivity()).getPath(), m_avatar,options);
		
	}

	@Override
	public void onClick(View v) {
		Intent it = null;
		switch (v.getId()) {
		case R.id.sport_parent:
			it = new Intent(getActivity(), SportsListActivity.class);
			startActivity(it);
			break;
		case R.id.medication:
			it = new Intent(getActivity(), MedicationListActivity.class);
			it.putExtra("type", 0); // 大人用药记录 0
			startActivity(it);
			break;
		case R.id.m_avatar:
			it=new Intent(getActivity(), ParentEditActivity.class);
			startActivity(it);
			break;
		default:

			break;

		}

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
			user = UserCache.getOauth(getActivity());
			if(user!=null){
			mName.setText(user.getUserName());
			mPhone.setText(user.getMobile());
			mDevice.setText(user.getDeviceNo());
			getData(user.getUserId());
			}
			

	}

	private void getData(String customerId) {

		Uri.Builder builder = Uri.parse(Constants.GET_MED_SPORT).buildUpon();
		builder.appendQueryParameter("customerId", customerId + "");

		RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
		Log.d("GET_MED_SPORT", "GET_MED_SPORT" + builder.toString());
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
				Request.Method.GET, builder.toString(), null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {

						Log.d("GET_MED_SPORT",
								"GET_MED_SPORT" + arg0.toString());
						try {
							MedPercentAndSportResult a = new Gson().fromJson(
									arg0.toString(),
									MedPercentAndSportResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {

								MedPercentAndSport result = a.getRows();
								
								setMotherInfo(result);
							} else {
								Toast.makeText(getActivity(), a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						
						Toast.makeText(getActivity(),
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});
		requestQueue.add(jsonObjectRequest);
	}

	
	
	
	/**
	 * 设置页面的基本信息
	 * @param med
	 */
	private void setMotherInfo(MedPercentAndSport med){
		mNextMed.setText(med.getNextMedDate());
		m_med.setText(med.getMedicationName());
		//设置卡路里
		String cal=med.getCalorie();
		if(cal!=null&&cal.length()>0){
			m_calorie.setText(getString(R.string.cal_hint1)+med.getCalorie()+getString(R.string.cal_hint2));
		}
		//设置步行的公里数
		String mil=med.getMileage();
		if(mil!=null&&mil.length()>0){
			m_m.setText(getString(R.string.step_hint1)+mil+getString(R.string.step_hint2));
		}
		//设置家长的头像	
		if(user.getPath()!=null){
			ImageLoader.getInstance().displayImage(user.getPath(), m_avatar,options);
		}
		String medecentNumString= med.getMedPecentNum();
		if(medecentNumString!=null&&medecentNumString.length()>0){
				donutProgress.setProgress(Integer.parseInt(medecentNumString));
		}
		//设置步数
		String step=med.getSteps();
		if(step!=null&&step.length()>0){
		m_step.setText(step);
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 显示进度加载框
	 */
	public void show() {

		if (loadingDialog == null) {
			loadingDialog = LoadingDialog.createDialog(getActivity());
			// 点击外部区域，是否消失loadingDialog
			loadingDialog.setCanceledOnTouchOutside(false);
		}
		loadingDialog.setMessage("正在加载");
		loadingDialog.show();
	}

	/**
	 * 关闭进度加载框
	 */
	public void dissMiss() {
		if (loadingDialog != null) {
			loadingDialog.dismiss();
			loadingDialog = null;
		}
	}

}
